cap program drop balance
program balance
	version 16.1
	clear 
	set type double 
	args bidder_auction
	set obs 8192
	gen com_n = _n
	gen com_group = ""
	sort com_n
	qui gen DB_decimal = _n - 1 if _n <= 8192
	qui egen DB_binary = base(DB_decimal)  /*** ssc install egenmore if necessary ****/

	pause on
	gen DB_binary_opposite = usubinstr(DB_binary, "0", "2",.)
	replace DB_binary_opposite = usubinstr(DB_binary_opposite, "1", "0",.)
	replace DB_binary_opposite = usubinstr(DB_binary_opposite, "2", "1",.)

	destring DB_binary, gen(DB_binary_real)
	destring DB_binary_opposite, gen(DB_binary_opposite_real)
	gen com_n_opposite = 8192 - com_n

	* group 
	gen g28_plus = _n if _n < 29
	
	
	/* pair */
	gen pair28 = 1 if g28_plus == 1 | g28_plus == 7 /*道央南（14）,紋別・網走	31*/
	replace pair28 = 2 if g28_plus == 6 | g28_plus == 8 /*釧路・根室	14,小樽・ニセコ	14*/
	replace pair28 = 3 if g28_plus == 2 | g28_plus == 3 /*道央北	8,函館松前	10*/
	replace pair28 = 4 if g28_plus == 4 | g28_plus == 5 /*留萌	4,稚内	4*/
	*造園
	replace pair28 = 5 if g28_plus == 9 | g28_plus == 14 /*茨城造園	10,大分造園	5*/
	replace pair28 = 6 if g28_plus == 26 | g28_plus == 27 /*福井造園	1,釧路造園	3*/
	*西日本道路
	replace pair28 = 7 if g28_plus == 12 | g28_plus == 22 /*島根道路	3,愛媛道路	4*/
	replace pair28 = 8 if g28_plus == 18 | g28_plus == 25 /*岐阜標識	2,四国道路	1*/
	
	*あまり、ringirmsの数の多い順に割り振り020319
	replace pair28 = 9 if g28_plus == 10 | g28_plus == 16 /*山形	32,静岡三島	24,数が多い*/
	replace pair28 = 10 if g28_plus == 11 | g28_plus == 19 /*秋田	11,愛知・岐阜	18*/
	replace pair28 = 11 if g28_plus == 17 | g28_plus == 20 /*岐阜・長野	8,静岡菊川	6*/
	replace pair28 = 12 if g28_plus == 23 | g28_plus == 28 /*青森	3,徳島	6*/
	replace pair28 = 13 if g28_plus == 13 | g28_plus == 15 /*岐阜電気	2,新潟	2*/

	merge m:1 g28_plus using ../fishertest/group_treatment.dta
	drop _merge

	qui gen group_id_min = .
	qui gen group_id_max = .
	forvalues x = 1(1)13{
		qui sum g28_plus if pair28 == `x'
		qui replace group_id_min = `r(min)' if _n == `x'
		qui replace group_id_max = `r(max)' if _n == `x'
	}
	
	
	forvalues m = 1(1)8192{
		sort com_n
		local thebinary = DB_binary[`m']
		*di as result strofreal(DB_decimal[`m']) + ": " _continue
		local S = ""
		forvalues x = 1(1)13{
			local bi = substr("`thebinary'", `x',1)
			*di "`bi'" _continue
			if "`bi'" == "0"{
				local S = "`S' " + strofreal(group_id_min[`x'])
			}
			else{
				local S = "`S' " + strofreal(group_id_max[`x'])
			}
		}
		local S = ustrregexra("`S'", "^ ","")
		*di "; `S'" /*[`c(current_time)' `c(current_date)'; begins at `start_time']"*/
		*computation "`MODE'" "`PERIOD'" "& random_treatment == `t'" "if com_n == `m'" "rdrobust_on"
		qui replace com_group = "`S'" if com_n == `m'
	}
	gen ttest_wbp = .
	gen ttest_partic = .
	gen ttest_mints1 = .
	
	save ../fishertest/balance_pattern.dta, replace


/* biddata+firmIDdata読み込み*/

set type double
*cap drop afterwards*
*cap drop after
use "../data/biddata020119.dta", clear
merge 1:1 rid using "../data/rid_address_license_firmID_020119.dta"
drop _merge
/* data period 2015-2018*/
	keep if fy_con > 2014 & fy_con < 2018
/* fill brank firm address and license no.*/ 
	replace ad_firm = ad_firm_new if ad_firm=="" & ad_firm_new ~= ""
	replace no_license = no_license_new if no_license == . & no_license_new < .
	drop *_new
	drop tend_date cont_date
	drop second_round rank1_q rank1
/* recounstruct regionfirmTG based on bigger sample*/
	egen regionfirmTG = tag(region firmID)

/* partic,mintsをfirmtestsから取得*/
	merge 1:1 rid region using "../firmleveltest/test_sample_with_results.dta"
	drop regionfirmID - ftt_hr2p rank1_q - neg_ftt_ts1s tsrank
	*partic,mints1のどっとを埋める
	sort region firmID partic
	by region firmID: replace partic = partic[_n-1] if partic[_n-1] < . & _n > 1
	by region firmID: replace mints1 = mints1[_n-1] if mints1[_n-1] < . & _n > 1
	drop _merge

/* 242 firms */
	merge m:1 firmID region using "../data/ring_list020119.dta"
	drop _merge

/* cluster */
	merge m:1 firmID region using "../firmleveltest/ringfirms_plus.dta"
	drop c1 - c1455
	rename g* g*_plus
	compress
	drop _merge
	
	***************************************************************************
	replace partic = . if g28_plus == .
	replace mints1 = . if g28_plus == .
	***************************************************************************
	bys id: egen min_tech = min(sc_tech)
	bys id: egen max_tech = max(sc_tech)
	gen FLAG_score = 0
	replace FLAG_score = 1 if max_tec < 100
	drop if min_tech < 100 & max_tech > 100 /*+100されていないbidderがいる（あ）*/
	drop if max_tech > 250					/*drop price-only auctions*/

	tempvar temp_date
	qui gen `temp_date' = strofreal(year_bid) + "/" + strofreal(mo_bid) + "/" + strofreal(day_bid)
	cap gen MDYbid = date(`temp_date', "YMD")
	format MDYbid %td
	gen after = 1 if MDYbid >= td(15mar2019) & MDYbid < td(01apr2021)
	replace after = 0 if MDYbid <= td(12feb2019) & MDYbid >= td(01apr2015)
	keep if fy_con < 2018 & after == 0
	
	cap drop regionfirmTG
	egen regionfirmTG = tag(regionfirmID)
	sort nm_project n_bd_rd1
	
	keep win_bid_pct partic mints1 ring_firm *regionfirmTG* g28_plus after id winner
	
	***************************************************************************
	bys id: egen g28_max = max(g28_plus) 
	drop if g28_max == .
	***************************************************************************
	
	gen com_n = _n
	gen g28_plus_string = strofreal(g28_plus) if g28_plus < .
	merge 1:1 com_n using ../fishertest/balance_pattern.dta
	
	cap drop _merge	
	forvalues i = 1(1)4096{
		local i_oppose = 8193 - `i'
		sort com_n
		local A = com_group[`i']
		local AA = usubinstr("`A'", " ","|",.)
		local B = DB_binary[`i']
		local A_opposite = com_group[`i_oppose']
		local AA_opposite = usubinstr("`A_opposite'", " ","|",.)
		local B_opposite = DB_binary[`i_oppose']
		*di "[`i']: `AA'; `B' / [`i_oppose']: `AA_opposite'; `B_opposite'; "
		di "[`i']: `AA'; `B';" _continue
		cap drop themarkets
		tempvar tempv
		qui gen `tempv' = ustrregexm(g28_plus_string, "^(?:`AA')$") ///
			if g28_plus != 21 & g28_plus != 24 & g28_plus < .
		if "`bidder_auction'" == "auction"{
			qui bys id: egen themarkets = max(`tempv')
		}
		else{
			qui gen themarkets = `tempv'
		}
		cap drop `tempv'
		qui ttest win_bid_pct if winner == 1 & ring_firm == 1 & after == 0, by(themarkets)
		local ttest_wbp = `r(p)'
		di "ttest wbp: " string(`r(p)',"%6.3f" ) _continue
		qui ttest partic if ring_firm == 1 & regionfirmTG == 1, by(themarkets)
		local ttest_partic = `r(p)'
		di "; participation: " string(`r(p)', "%6.3f") _continue
		qui ttest mints1 if ring_firm == 1 & regionfirmTG == 1, by(themarkets)
		local ttest_mints1 = `r(p)'
		di "; tstat: " string(`r(p)', "%6.3f")  
		
		qui replace ttest_wbp = `ttest_wbp' if com_n == `i' | com_n == `i_oppose'
		qui replace ttest_partic = `ttest_partic' if com_n == `i' | com_n == `i_oppose'
		qui replace ttest_mints1 = `ttest_mints1' if com_n == `i' | com_n == `i_oppose'
		cap drop themarkets
	}
	drop if com_n > 8192
	save ../fishertest/balance.dta, replace
end
